<?php

namespace App\Admin\Middleware;
use App\Admin\Service\Base\RolePermissionsService;
use App\Common\Exception\ApiMessageException;
use App\Common\Util\AdminAuth;
use App\Common\Util\Response;
use App\Common\Util\TP;
use App\Request;
use Psr\Http\Message\ServerRequestInterface;
use Sc\Util\Tool;

/**
 * 权限验证
 */
class PermissionsMiddleware
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @return \think\Response
     * @throws ApiMessageException|\Throwable
     */
    public function handle(Request $request, \Closure $next): \think\Response
    {
         RolePermissionsService::aop(false)->init();

        if (!RolePermissionsService::aop(false)->check(Tool::url(TP::request()->url()), (array)AdminAuth::getInfo()->role_ids)) {
            if (str_contains(current((array)$request->header('accept')), 'application/json')) {
                throw new ApiMessageException("权限不足");
            }

            return Response::html("权限不足");
        }

        return $next($request);
    }
}